/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/* eslint-disable import/no-extraneous-dependencies */
import React, { useEffect, useState } from 'react';
import { connect } from 'dva';
import { Button, Col, Form, Input, message, Row, Select, Spin, Popconfirm } from 'antd';
import StandardTable from '@/components/StandardTable';

import DispatSettingModal from './DispatSettingModal';

const FormItem = Form.Item;
const { Option } = Select;

const DispatSetting = props => {
  const {
    form,
    dispatch,
    stationing,
    stationList = [],
    loading,
    settingList = {},
    deliveryPaySetInfo,
    companyInfo = {},
  } = props;
  const { getFieldDecorator, validateFields } = form;
  const [selectRows, setSelectRows] = useState([]);
  const [visible, setVisible] = useState(false);
  const { list = [] } = settingList;

  const onSubmit = pageOptions => {
    const { current, pageSize = 20 } = pageOptions;
    validateFields((error, values) => {
      if (error) return;
      dispatch({
        type: 'dispatStatistics/getSettingList',
        payload: {
          ...values,
          page: current || 1,
          pageSize,
          channel: 'DeliveryFeeDirectPayment',
        },
      });
    });
  };
  form.reload = () => onSubmit(settingList.pagination || {});

  const setMultiEditDeliveryPayStatus = data => {
    dispatch({
      type: 'dispatStatistics/multiEditDeliveryPayStatus',
      payload: data,
    }).then(() => {
      setSelectRows([]);
      form.reload();
    });
  };

  const setCourierInfo = record => {
    const { id, is_delivery_pay } = record;
    setMultiEditDeliveryPayStatus({
      ids: id,
      status: is_delivery_pay === '1' ? '0' : '1',
    });
  };

  const mutipleSetPayStatus = type => {
    const formatList = selectRows
      .filter(item => item.is_delivery_pay !== type)
      .map(item => item.id);
    if (formatList.length === 0) {
      message.error(`当前选择列已${type === '1' ? '开启' : '关闭'}权限`);
      return;
    }
    setMultiEditDeliveryPayStatus({
      ids: formatList.toString(),
      status: type,
    });
  };

  const onOpenModal = () => {
    dispatch({
      type: 'dispatStatistics/getDeliveryPaySetInfo',
    }).then((data = {}) => {
      const { brandInfo = [] } = data;
      const formatList = Array.isArray(brandInfo) ? brandInfo : [];
      if (formatList.length) {
        setVisible(true);
      } else {
        message.error('未获取到品牌配置');
      }
    });
  };

  useEffect(() => {
    dispatch({
      type: 'station/getStationList',
    });
  }, []);

  useEffect(
    () => {
      if (list.length === 0) {
        form.reload();
      }
    },
    [list.length],
  );

  const columns = [
    {
      title: '快宝工号',
      dataIndex: 'courier_no',
      key: 'courier_no',
      align: 'center',
    },
    {
      title: '所属站点',
      dataIndex: 'site_name',
      key: 'site_name',
      align: 'center',
      render: text => text || companyInfo?.brand_name || '--',
    },
    {
      title: '业务员',
      align: 'center',
      render: (text, record) => `${record.courier_name}-${record.courier_phone}`,
    },
    {
      title: '状态',
      align: 'center',
      render: record => (
        <>
          <span style={{ marginRight: 20 }}>
            {record.is_delivery_pay === '1' ? '已开启' : '已关闭'}
          </span>
          <Popconfirm
            placement="top"
            title={`确定${
              record.is_delivery_pay === '1' ? '关闭' : '开启'
            }该业务员的直发派费权限？`}
            onConfirm={() => setCourierInfo(record)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="primary" size="small">
              {record.is_delivery_pay === '1' ? '关闭' : '开启'}
            </Button>
          </Popconfirm>
        </>
      ),
    },
  ];

  return (
    <>
      <Row type="flex" justify="space-between">
        <Col>
          <Form layout="inline" style={{ marginBottom: 24 }}>
            <FormItem label="公司站点">
              {getFieldDecorator('site_id', {
                initialValue: 'all',
              })(
                <Select
                  // onFocus={onGetStationList}
                  // onSelect={onSelectStation}
                  placeholder="请选择公司站点"
                  allowClear
                  style={{ width: 180 }}
                >
                  {stationing ? (
                    <Option disabled value="loading">
                      <Spin />
                    </Option>
                  ) : (
                    <Option key="all" value="all">
                      全部站点
                    </Option>
                  )}
                  <Option key="0" value="0">
                    {companyInfo && companyInfo.brand_name}
                  </Option>
                  {stationList.map(({ site_code, site_name, site_id }) => (
                    <Option key={site_code} value={site_id}>
                      {site_name}
                    </Option>
                  ))}
                </Select>,
              )}
            </FormItem>
            <FormItem label="业务员">
              {getFieldDecorator('search')(
                <Input
                  allowClear
                  style={{ width: 250 }}
                  placeholder="请输入业务员姓名或手机号搜索"
                />,
              )}
            </FormItem>
            <FormItem>
              <Button type="primary" onClick={onSubmit}>
                查询
              </Button>
            </FormItem>
          </Form>
        </Col>
        <Col>
          <Button type="primary" onClick={onOpenModal}>
            派费及发放设置
          </Button>
        </Col>
      </Row>
      <StandardTable
        selectedRows={selectRows}
        onSelectRow={setSelectRows}
        rowKey="id"
        loading={loading}
        data={settingList}
        columns={columns}
        scroll={{ x: 800 }}
        onChange={onSubmit}
      />
      <Row type="flex" gutter={[20, 20]} style={{ margin: 0 }}>
        <Col>
          <Button
            onClick={() => mutipleSetPayStatus('1')}
            disabled={!(selectRows.length && selectRows.some(item => item.is_delivery_pay === '0'))}
            type="primary"
          >
            批量开启权限
          </Button>
        </Col>
        <Col>
          <Button
            onClick={() => mutipleSetPayStatus('0')}
            disabled={!(selectRows.length && selectRows.some(item => item.is_delivery_pay === '1'))}
            type="primary"
          >
            批量关闭权限
          </Button>
        </Col>
      </Row>
      <DispatSettingModal
        visible={visible}
        title="派费及发放设置"
        onCancel={() => setVisible(false)}
        deliveryPaySetInfo={deliveryPaySetInfo}
      />
    </>
  );
};

export default connect(({ loading, station, dispatStatistics }) => ({
  loading: loading.effects['dispatStatistics/getSettingList'],
  stationList: station.list || [],
  companyInfo: station.company_info || {},
  stationing: loading.effects['station/getStationList'],
  tableList: [],
  dispatStatistics,
  settingList: dispatStatistics.settingList || [],
  deliveryPaySetInfo: dispatStatistics.deliveryPaySetInfo || {},
}))(React.memo(Form.create()(DispatSetting)));
